package com.wjy.api.wechat;

import cn.binarywang.wx.miniapp.util.crypt.WxMaCryptUtils;
import com.alibaba.fastjson.JSONObject;
import com.wjy.bean.offical.RegisterWXAuthor;
import com.wjy.bean.offical.UserInfo;
import com.wjy.dao.wechat.AuthorDao;
import com.wjy.exception.business.BusinessException;
import com.wjy.exception.system.SystemException;
import com.wjy.jedis.RedisUtil;
import com.wjy.response.ResponseBuilder;
import com.wjy.send.mail.VerifyCode;
import lombok.extern.log4j.Log4j2;

import javax.ws.rs.*;
import javax.ws.rs.core.Response;

@Log4j2
@Path(value = "/wechat/author")
@Produces(value = "application/json;charset=utf-8")
public class AuthorAPI {

    private AuthorDao authorDao = new AuthorDao();

    @GET
    @Path(value = "/loginAuthor")
    public Response loginAuthor(@QueryParam(value = "code") String code) throws Exception {

        log.info("code: " + code);

        return ResponseBuilder.success(authorDao.loginAuthor(code));

    }

    @GET
    @Path(value = "/sendVerifyCode")
    public Response sendVerifyCode(@QueryParam(value = "wxAuthorEmail") String wxAuthorEmail) throws Exception {

        log.info("wxAuthorEmail: " + wxAuthorEmail);

        VerifyCode verifyCode = new VerifyCode();

        if (authorDao.verifyEmail(wxAuthorEmail)) {
            if (verifyCode.send(wxAuthorEmail).getInteger("code") != 200) {
                throw new SystemException("验证码发送失败");
            }
        } else {
            throw new BusinessException("该邮箱已注册");
        }

        return ResponseBuilder.success("验证码发送成功");

    }

    @POST
    @Path(value = "/registerAuthor")
    public Response registerAuthor(RegisterWXAuthor registerWXAuthor) throws Exception {

        log.info("RegisterWXAuthorBean: " + registerWXAuthor);

        String VerifyCode = RedisUtil.get("verifycode:" + registerWXAuthor.getWxAuthorEmail());

        if (!VerifyCode.equals(registerWXAuthor.getVerifyCode())) {
            throw new BusinessException("验证码错误，请重新输入");
        }

        String text = WxMaCryptUtils.decrypt(registerWXAuthor.getSessionKey(), registerWXAuthor.getEncryptedData(),
                registerWXAuthor.getIv());

        UserInfo userInfo = JSONObject.parseObject(text, UserInfo.class);

        log.info("UserInfo:" + userInfo);

        return ResponseBuilder.success(authorDao.registerAuthor(registerWXAuthor.getWxAuthorEmail(), userInfo));

    }

}
